package fhp.hlhj.giantfold.fragment
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RelativeLayout
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.PlatformActionListener
import cn.sharesdk.onekeyshare.OnekeyShare
import cn.sharesdk.wechat.friends.Wechat
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.liaoinstan.springview.widget.SpringView
import com.lzy.okgo.model.HttpParams
import fhp.hlhj.giantfold.Contents
import fhp.hlhj.giantfold.MainActivity
import fhp.hlhj.giantfold.R
import fhp.hlhj.giantfold.activity.GainDetailAty
import fhp.hlhj.giantfold.activity.annualized.AnnualizedAty
import fhp.hlhj.giantfold.activity.login.WechatLoginAty
import fhp.hlhj.giantfold.activity.message.MessageAty
import fhp.hlhj.giantfold.activity.message.MessageDetailAty
import fhp.hlhj.giantfold.activity.red.DayRed
import fhp.hlhj.giantfold.activity.red.ShakeRedAty
import fhp.hlhj.giantfold.activity.user.BindPhoneAty
import fhp.hlhj.giantfold.activity.user.GetCashAty
import fhp.hlhj.giantfold.activity.user.UserCenter
import fhp.hlhj.giantfold.customView.MyHeader
import fhp.hlhj.giantfold.interfaces.IAdv
import fhp.hlhj.giantfold.interfaces.IUser
import fhp.hlhj.giantfold.javaBean.AdvBean
import fhp.hlhj.giantfold.javaBean.UserInfoBean
import fhp.hlhj.giantfold.network.Urls
import fhp.hlhj.giantfold.presenter.AdvPresenter
import fhp.hlhj.giantfold.presenter.UserPresenter
import fhp.hlhj.giantfold.utils.LogUtil
import fhp.hlhj.giantfold.utils.MyUtils
import fhp.hlhj.giantfold.utils.SPUtils
import kotlinx.android.synthetic.main.fgm_growmoeny.view.*
import java.text.DecimalFormat
import java.util.ArrayList
import java.util.HashMap

/**
 * author: FHP
 * data: on 2017\11\18 0018 15:08
 * E-Mail: 103945089@qq.com
 */
class GrowMoneyFgm :Fragment(), IUser,IAdv, SpringView.OnFreshListener {


    private lateinit var rootView:View
    private lateinit var userPresetner:UserPresenter
    private lateinit var advPresenter:AdvPresenter
    private var fourData=ArrayList<String>()
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        rootView=inflater.inflate(R.layout.fgm_growmoeny,null)
        initListenter()
        initData()
        setSpView()
        userPresetner= UserPresenter(this)
        advPresenter= AdvPresenter(this)

        /*用户信息*/
        val httpParams = HttpParams()
        httpParams.put("user_id",Contents.userId)
        userPresetner.getUser(httpParams)

        /*广告位*/

        val params = HttpParams()
        params.put("block",4)
        advPresenter.getAdv(params)
        return rootView
    }
    private fun initData() {


        /*菜单*/
        fourData.clear()
        fourData.add("")
        fourData.add("")
        fourData.add("")
        val toolAdp: BaseQuickAdapter<String, BaseViewHolder> = object : BaseQuickAdapter<String, BaseViewHolder>(R.layout.red_item, fourData) {
            override fun convert(helper: BaseViewHolder?, item: String?) {
                when(helper?.layoutPosition){
                    0->{
                        val lo = helper?.getView<RelativeLayout>(R.id.lo)
                        val params = lo.layoutParams as RecyclerView.LayoutParams
                        helper?.setImageResource(R.id.img,R.mipmap.tthb)
                    }
                    1->{
                        val lo = helper?.getView<RelativeLayout>(R.id.lo)
                        val params = lo.layoutParams as RecyclerView.LayoutParams
                        params.setMargins(30,0,0,0)

                        helper?.setImageResource(R.id.img,R.mipmap.yhb)
                    }
                    2->{
                        val lo = helper?.getView<RelativeLayout>(R.id.lo)
                        val params = lo.layoutParams as RecyclerView.LayoutParams
                        params.setMargins(30,0,0,0)

                        helper?.setImageResource(R.id.img,R.mipmap.hyll)
                    }
                }
            }
        }
        rootView.recyclerview.adapter= toolAdp
        rootView.recyclerview.layoutManager=LinearLayoutManager(context,LinearLayout.HORIZONTAL,false)
            toolAdp.setOnItemClickListener { adapter, view, position ->
                when(position){
                    0->{
                        if (Contents.userId.equals("0")){
                            val intent =Intent(activity, WechatLoginAty::class.java)
                            activity.startActivityFromFragment(this,intent,1)
                        }else{

                            context.startActivity(Intent(context,DayRed::class.java))
                        }
                    }
                    1->{
                        if (Contents.userId.equals("0")){
                            val intent =Intent(activity, WechatLoginAty::class.java)
                            activity.startActivityFromFragment(this,intent,1)
                        }else{

                            context.startActivity(Intent(context,ShakeRedAty::class.java))
                        }
                    }
                    2->{
                        if (Contents.userId.equals("0")){
                            val intent =Intent(activity, WechatLoginAty::class.java)
                            activity.startActivityFromFragment(this,intent,1)
                        }else{
                            showShare()

                        }
                    }
            }
        }
    }
    private fun showShare() {
        val oks = OnekeyShare()

        oks.callback=object : PlatformActionListener {
            override fun onComplete(p0: Platform?, p1: Int, p2: HashMap<String, Any>?) {
            }

            override fun onCancel(p0: Platform?, p1: Int) {
            }

            override fun onError(p0: Platform?, p1: Int, p2: Throwable?) {
                LogUtil.log("错误$p2")
            }
        }
        //关闭sso授权
        oks.disableSSOWhenAuthorize()
        // title标题，印象笔记、邮箱、信息、微信、人人网、QQ和QQ空间使用
        oks.setTitle("巨折")
        // titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
//        oks.setTitleUrl("http://pintu.hlhjapp.com/index.php?m=home&c=user&a=inviteCode&username=" )
        // text是分享文本，所有平台都需要这个字段
        oks.text = "巨折：给好友加油啦！！"
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg")
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
//        oks.setUrl("http://juzhe.kkgrow.com/web/share5.html?a=${MyUtils.formatDouble(Contents.userInfo?.annual_rate?.toDouble()!!,2)}&b=${MyUtils.formatDouble(Contents.userInfo?.online_sp_accumulated_consume!!.toDouble(),2)}&c=${MyUtils.formatDouble(Contents.userInfo?.earnings_today!!.toDouble(),2)}" )
        oks.setUrl("http://juzhe.kkgrow.com/web/share5.html?a=${Contents.userId}" )
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//        oks.setComment("我是测试评论文本")
        // site是分享此内容的网站名称，仅在QQ空间使用
//        oks.setSite("ShareSDK")
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
//        oks.setSiteUrl("http://pintu.hlhjapp.com/index.php?m=home&c=user&a=inviteCode&username=")
        // 启动分享GUI
//        oks.setPlatform(Wechat.NAME)
        oks.show(context)

    }

    override fun onResume() {
        super.onResume()
        LogUtil.log("生钱OnResume----刷新数据${Contents.userId}")
        val params = HttpParams()
        params.put("block",4)
        advPresenter.getAdv(params)


        /*用户信息*/
        val httpParams = HttpParams()
        httpParams.put("user_id",Contents.userId)
        userPresetner.getUser(httpParams)

        /**
         * 根据登录类型判断
         *//*
        LogUtil.log("OnResum")
        LogUtil.logi("登录类型${SPUtils.readLoginType(context)}userId=${Contents.userId}")
        when(SPUtils.readLoginType(context)){
            -1->{
                rootView.btSelf.setOnClickListener{
                    val intent =Intent(activity, WechatLoginAty::class.java)
                    activity.startActivityFromFragment(this,intent,1)
                }
                Glide.with(context).load(R.mipmap.exp5).asBitmap().dontAnimate().into(rootView.btSelf)
            }
            else->{
                if (Contents.userId.equals("0")){
                    rootView.btSelf.setOnClickListener{
                        context.startActivity(Intent(context, BindPhoneAty::class.java))
                    }
                }else{
                    val httpParams = HttpParams()
                    httpParams.put("user_id",Contents.userId)
                    userPresetner.getUser(httpParams)
                    rootView.btSelf.setOnClickListener{
                        val intent = Intent(context, UserCenter::class.java)
                        activity.startActivityForResult(intent,2)
//                        context.startActivity()
                    }
                }

            }
        }*/
    }
    private fun initListenter() {
        rootView.btSelf.setOnClickListener {
            if (Contents.userId.equals("0")){
                val intent =Intent(activity, WechatLoginAty::class.java)
                activity.startActivityFromFragment(this,intent,1)
            }else{
                context.startActivity(Intent(context,UserCenter::class.java))
            }
        }
        rootView.btDetail.setOnClickListener {
            if (Contents.userId.equals("0")){
                val intent =Intent(activity, WechatLoginAty::class.java)
                activity.startActivityFromFragment(this,intent,1)
            }else{

                context.startActivity(Intent(context,GainDetailAty::class.java))
            }
        }
        rootView.arcProgress.setOnClickListener {
            if (Contents.userId.equals("0")){
                val intent =Intent(activity, WechatLoginAty::class.java)
                activity.startActivityFromFragment(this,intent,1)
            }else{

                context.startActivity(Intent(context,AnnualizedAty::class.java))
            }
        }
        rootView.btMessage.setOnClickListener {
            if (Contents.userId.equals("0")){
                val intent =Intent(activity, WechatLoginAty::class.java)
                activity.startActivityFromFragment(this,intent,1)
            }else{

                context.startActivity(Intent(context,MessageAty::class.java))
            }
        }
        rootView.btGetCash.setOnClickListener {
            if (Contents.userId.equals("0")){
                val intent =Intent(activity, WechatLoginAty::class.java)
                activity.startActivityFromFragment(this,intent,1)
            }else{
                context.startActivity(Intent(context,GetCashAty::class.java))

            }
        }
        rootView.btSelf.setOnClickListener {
            if (Contents.userId.equals("0")){
                val intent =Intent(activity, WechatLoginAty::class.java)
                activity.startActivityFromFragment(this,intent,1)
            }else{
                val intent = Intent(context, UserCenter::class.java)
                activity.startActivityForResult(intent,2)
            }
        }
    }
    override fun showLoading() {
    }
    /**
     * 轮播设置
     */
    private fun setSpView() {
        rootView.spView.header= MyHeader()
        rootView.spView.callFresh()
        rootView.spView.setListener(this)
    }
    override fun getUser(userInfoBean: UserInfoBean) {
        if (userInfoBean.code==200&&context!=null){
            Contents.userInfo=userInfoBean.data
            Glide.with(context).load(Urls.BaseUrl+"/"+userInfoBean.data.head_pic).asBitmap().dontAnimate().placeholder(R.mipmap.placeholdericon).into(rootView.btSelf)
            val df = DecimalFormat("0.000")
            val userInfo = userInfoBean.data
//        rootView.arcProgress.progress=userInfo?.annual_rate?.toInt()!!
            LogUtil.log("生钱刷新页面----------${Contents.userId}")
            if (!Contents.userId.equals("0")){
                rootView.totalIncrease.text="累计收入${df.format(userInfo?.earnings_accumulated?.toDouble()).toString()}"
                rootView.todayMoney.text=df.format(userInfo?.earnings_today?.toDouble()).toString()
                rootView.spentMoney.text=df.format(userInfo?.principal?.toDouble()).toString()
                rootView.availableMoney.text=df.format(userInfo?.balance?.toDouble()).toString()
                rootView.totalSpentNum.text="花销笔数${userInfo.consume_number}"
            }else{
                LogUtil.log("生钱刷新设置为0")
                rootView.totalIncrease.text="累计收入0.00"
                rootView.todayMoney.text="0.00"
                rootView.spentMoney.text="0.00"
                rootView.availableMoney.text="0.00"
                rootView.totalSpentNum.text="花销笔数0"
            }
        }else{
            Glide.with(context).load(R.mipmap.placeholdericon).asBitmap().dontAnimate().placeholder(R.mipmap.placeholdericon).into(rootView.btSelf)
            rootView.totalIncrease.text="累计收入0.00"
            rootView.todayMoney.text="0.00"
            rootView.spentMoney.text="0.00"
            rootView.availableMoney.text="0.00"
            rootView.totalSpentNum.text="花销笔数0"

        }
    }
    /*广告*/
    override fun getADV(advBean: AdvBean) {
        if (advBean.code==200){
            Glide.with(context).load(Urls.BaseUrl+advBean.data[0].adv_img).asBitmap().dontAnimate().into(rootView.fuliImg)
            if (advBean.data[0].jump_type.equals("1")){
                rootView.fuliImg.setOnClickListener {
                    val intent = Intent(context, MessageDetailAty::class.java)
                    intent.putExtra("url",advBean.data[0].jump_url)
                    context.startActivity(intent)
                }
            }
        }
    }

    /**
     * Spview监听
     */
    override fun onLoadmore() {
    }

    override fun onRefresh() {
        Thread {
            kotlin.run {
                LogUtil.log("shua")
                Thread.sleep(1000)
                rootView.post {
                    rootView.spView.onFinishFreshAndLoad()
                }
            }
        }.start()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        LogUtil.log("---------------------------来了来了$resultCode")

        if (resultCode!= Activity.RESULT_OK)return
        when(requestCode){
            1->{
                LogUtil.log("---------------------------来了来了")
                val ft = fragmentManager.beginTransaction()
                ft.hide(this)
                ft.commit()
                val mainActivity = activity as MainActivity
                mainActivity.change(R.id.rbSpend)
            }
        }
    }
}
